/*
 * Copyright (c) 2009 by unreserved.org.
 * All rights reserved.
 */

package org.unreserved.ladderplot;

import java.util.*;

/**
 * More or less same logic as in ModelTextRenderer. Find way to not
 * duplicate that code.
 * 
 * <p>NB: *Does* work with nested hgroups...
 */
public class HGroupTextRenderer implements TextRenderer {
    protected HGroup hgroup;
    protected TextCanvas canvas;
    protected TextRenderer[] tr;
    protected int height = 0;
    
    public HGroupTextRenderer(HGroup hgroup) {
        this.hgroup = hgroup;
    }
    
    public void render() {
        ArrayList<Event> events = hgroup.getEvents();
        int n = events.size();
        tr = new TextRenderer[n];
        
        for (int i = 0; i < n; i++) {
            Event ev = (Event) events.get(i);
            
            if (ev instanceof Message) {
                tr[i] = new MessageTextRenderer((Message) ev);
            } else if (ev instanceof Label) {
                tr[i] = new LabelTextRenderer((Label) ev, -1);
            } else if (ev instanceof HGroup) {
                tr[i] = new HGroupTextRenderer((HGroup) ev);
            }
            
            tr[i].render();
            
            if (tr[i].getHeight() > height) {
                height = tr[i].getHeight();
            }
        }
    }
    
    public int getHeight() {
        return height;
    }
    
    public void print(TextCanvas canvas, int linenum) {
        int linenum2;
        for (int i = 0; i < tr.length; i++) {
            int heightDiff = (height - tr[i].getHeight());
            switch (hgroup.getVAlignment()) {
            case TOP:
                linenum2 = linenum;
                break;
            case CENTER: 
                linenum2 = linenum + (heightDiff/2);
                break;
            case BOTTOM:
                linenum2 = linenum + heightDiff;
                break;
            default:
                throw new RuntimeException("can't happen");
            }
            tr[i].print(canvas, linenum2);
        }
    }
}
